//
//  MLStatusPictureView.swift
//  SinaWeibo
//
//  Created by 李亮亮 on 16/4/13.
//  Copyright © 2016年 Big Fish. All rights reserved.
//

import UIKit
import SDWebImage


private let pictrueCellId = "pictrueCellId"
/// 图片直接的间距
private let pictureCellMargin: CGFloat = 3
private let maxWidth = ScreenWidth - 2 * StatusCellMargin
private let itemWidth = (maxWidth - 2 * pictureCellMargin) / 3

class MLStatusPictureView: UICollectionView {

    //外界设置的模型数组
    var imageURLs: [MLStatusPicture]? {
        didSet {
            //根据模型数组的数量 计算配图视图的大小
            print(imageURLs?.count)
            let pSize = caculatePictureViewSize()
            //更新视图的大小
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(pSize)
            }
            
            ///更新测试数据
            testLabel.text = "\(imageURLs?.count ?? 0)"
            
            //刷新页面的数据
            self.reloadData()
        }
    }
    
    
    //根据配图的数量计算配图的大小
    //1.单张图片显示图片原比例尺寸
    //2.四张图片  2 * 2
    //3. 其他的张图片就按照 3 * n(根据图片数量来计算)
    private func caculatePictureViewSize() -> CGSize {
        
        let imageCount = imageURLs?.count ?? 0
        //没有图片
        if imageCount == 0 {
            return CGSizeZero
        }
        //获取固定值
        
        //单张图片
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        if imageCount == 1 {
            //TODO 后期完善
            let imageSize = CGSize(width: 100, height: 150)
            //将layout的itemsize设置和配图一般大
            
            layout.itemSize = imageSize
            return imageSize
        }
        
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //四张图片
        if imageCount == 4 {
            let w = itemWidth * 2 + pictureCellMargin
            return CGSize(width: w, height: w)
        }
        
        //程序走到这里 一定是 其他的多张图片
        /*
         1,2,3   - 1
         4,5,6,  - 2
         7,8,9   - 3
         */
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let h = row * itemWidth + (row - 1) * pictureCellMargin
        return CGSize(width: maxWidth, height: h)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        //        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
        //注册cell
        self.registerClass(PictureCell.self, forCellWithReuseIdentifier: pictrueCellId)
        //设置数据源代理
        self.dataSource = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            
        }
        self.backgroundColor = UIColor(white: 0.9, alpha:1)
    }
    
    private lazy var testLabel: UILabel = UILabel(text: "", textColor: UIColor.redColor(), fontSize: 30)
    
}

//MARK: 数据源方法
extension MLStatusPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //注册cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictrueCellId, forIndexPath: indexPath) as! PictureCell
        //设置测试时yanse
        //        cell.backgroundColor = randomColor()
        cell.statusPicture = imageURLs![indexPath.item]
        return cell
    }
    
}


class PictureCell: UICollectionViewCell {
    
    
    var statusPicture: MLStatusPicture? {
        didSet {
            //给图片赋值
            let url = NSURL(string: statusPicture?.thumbnail_pic ?? "")
            iconView.sd_setImageWithURL(url)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置UI界面
    private func setupUI() {
        contentView.addSubview(iconView)
        //设置约束
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }

    }
    
    //懒加载子视图
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        
        //设置填充模式
        iv.contentMode = .ScaleAspectFill
        //手写代码需要手动设置裁剪
        iv.clipsToBounds = true
        return iv
        
    }()

    
    
}
